package com.lagou.edu.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @author 胡益文
 * @since 2021/9/28 20:42
 */
public class ResourceUtil {

    /**
    * 功能描述:根据相对路径获取绝对路径
     * @author: hyw
     * @return:
     * @since: 2021/9/28 20:44
    */
    public static String getAbsolutePath(String path) throws UnsupportedEncodingException {
        String absolutePath = ResourceUtil.class.getResource("/").getPath();
        absolutePath = URLDecoder.decode(absolutePath,"utf-8");
        return absolutePath.replace("\\\\","/")+ path;
    }

    public static void readAndOut(InputStream inputStream, OutputStream outputStream) throws IOException {
        int contentSize = 0;
        //获取输入字符大小
        while (contentSize == 0){
            contentSize = inputStream.available();
        }
        //缓存数组读写
        int byteSize = 1024 ; //定义1024缓存
        int readNum = 0; //读取字符数
        byte[] bytes = new byte[byteSize];
        outputStream.write(HttpProtocolUtil.getHttpHeader200(contentSize).getBytes());
        while (readNum<contentSize){
            if(readNum+byteSize>contentSize){
                bytes = new byte[contentSize-readNum];
            }
            inputStream.read(bytes);//读取
            outputStream.write(bytes);//输出
            outputStream.flush();
            readNum+=byteSize;
        }
    }
}
